﻿// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var appData = Windows.Storage.ApplicationData.current;
    var activation = Windows.ApplicationModel.Activation;

    var storagePermissions = Windows.Storage.AccessCache.StorageApplicationPermissions;

    var permissionTokens = appData.localSettings.values["permissionTokens2"];

    if (permissionTokens) {
        permissionTokens = JSON.parse(permissionTokens);
    }
    else {
        permissionTokens = [];
        appData.localSettings.values["permissionTokens2"] = JSON.stringify(permissionTokens);
    }

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }


            var listVideo = document.getElementById("play-list-ul-id");
            var player = document.getElementById("video-player-id");
            var saveListButton = document.getElementById("save-playlist-button");
            var loadListButton = document.getElementById("load-playlist-button");

            listVideo.addEventListener("click", function (e) {
                var clickedTag = e.target;
                if (clickedTag.tagName.toLowerCase() == "li") {
                    player.src = clickedTag.getAttribute("data-video-file");
                    player.play();
                }
            });

            saveListButton.addEventListener("click", function () {
                var saveFilePicker = new Windows.Storage.Pickers.FileSavePicker();
                saveFilePicker.defaultFileExtension = ".txt";
                saveFilePicker.fileTypeChoices.insert("JSON", [".json"]);
                saveFilePicker.suggestedFileName = "New Playlist";

                saveFilePicker.pickSaveFileAsync().then(function (file) {
                    var items = listVideo.children;
                    var tokens = [];

                    for (var i = 0; i < items.length; i++) {
                        tokens.push(items[i].getAttribute("data-file-token"));
                    }

                    Windows.Storage.FileIO.writeTextAsync(file, JSON.stringify(tokens));
                });

            });

            loadListButton.addEventListener("click", function () {
                var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
                openPicker.fileTypeFilter.append(".json");
                openPicker.commitButtonText = "Pick play-list file";
                openPicker.pickSingleFileAsync().done(function (pickedFile) {
                    Windows.Storage.FileIO.readTextAsync(pickedFile).then(function (data) {
                        var tokens = JSON.parse(data);
                        for (var i = 0; i < tokens.length; i++) {
                            storagePermissions.futureAccessList.getFileAsync(tokens[i]).then(function (file) {
                                addVideo(file);
                            });
                        }

                    })
                });
            });

            var addVideoToList = function (fileName, realFile, token) {
                var videoItem = document.createElement("li");
                videoItem.setAttribute("data-file-token", token);
                videoItem.setAttribute("data-video-file", realFile);
                videoItem.innerText = fileName;
                var removeIcon = document.createElement("img");
                removeIcon.src = "images/remove-icon.png";
                removeIcon.height = 20;
                removeIcon.width = 20;
                videoItem.appendChild(removeIcon);

                removeIcon.addEventListener("click", function (e) {
                    var node = this.parentElement;
                    node.parentElement.removeChild(node);

                });
                listVideo.appendChild(videoItem);
            }
            var addMultipleVideoFiles = function (arrayVideoFiles) {
                for (var i = 0; i < arrayVideoFiles.length; i++) {
                    addVideo(arrayVideoFiles[i]);
                }
            };

            var addVideo = function (videoFile) {
                var realFile = URL.createObjectURL(videoFile);
                var fileName = videoFile.name;

                if (videoFile) {
                    var token = permissionTokens.length + videoFile.name;
                    storagePermissions.futureAccessList.addOrReplace(token, videoFile);

                    permissionTokens.push(token);
                    appData.localSettings.values["permissionTokens2"] = JSON.stringify(permissionTokens);
                    addVideoToList(fileName, realFile, token);
                }


                //var list = document.getElementById("play-list-ul-id");
                //var li = document.createElement("li");
                //li.innerText = realFile.;
                //list.appendChild(li);
            };

            //WinJS.Utilities.id("pick-file-button-id").listen("click", function () {
            //    var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
            //    openPicker.fileTypeFilter.replaceAll([".mp4"]);
            //    openPicker.pickSingleFileAsync().then(addVideo);
            //});

            WinJS.Utilities.id("pick-multiple-files-button-id").listen("click", function () {
                var multipleFilesPicker = new Windows.Storage.Pickers.FileOpenPicker();
                multipleFilesPicker.fileTypeFilter.replaceAll([".mp4"]);
                multipleFilesPicker.pickMultipleFilesAsync().then(addMultipleVideoFiles);
            });

            args.setPromise(WinJS.UI.processAll());
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    app.start();
})();